from flask import Blueprint, request
from utilsapp.mysql_con import db_pagelist, db_fetchone, db_delete, db_update,db_insert ,db_fetchall
from utilsapp.common import assign_value, parsing_data_id,get_operate
import json

from utilsapp.utils import ok
bluePrint = Blueprint('algorithm_config', __name__)
tableName = 'algorithm_config'


# 分页查询
@bluePrint.route('/getlist', methods=["post"])
def getlist():
    a = request.json
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    query = ""
    # if scoped != "":
        # query += f" and {scoped}"
    sql = f"""SELECT 
    algorithm_config.*, 
    sensor.sensor_name, 
    device.device_name, 
    algorithm_group.name,
    algorithm_group.m_code,
    algorithm_group.m_name
    FROM algorithm_config 
    LEFT JOIN sensor ON algorithm_config.sensor_id = sensor.id 
    LEFT JOIN device ON algorithm_config.device_id = device.id 
    LEFT JOIN algorithm_group ON algorithm_config.algorithm_group_id = algorithm_group.id 
    where 1=1 {query} 
    ORDER BY algorithm_config.id DESC"""
    res = db_pagelist(sql, a['page'], a['size'])
    return res



@bluePrint.route('/add', methods=['post'])
def add():
    sensor_id = assign_value(request.json, "sensor_id")
    device_id = assign_value(request.json, "device_id")
    algorithm_group_id = assign_value(request.json, "algorithm_group_id")
    config = assign_value(request.json, "config")
    is_enable = assign_value(request.json, "is_enable")
    for sid in sensor_id:
        data = {
            'sensor_id' : sid,
            'device_id' : device_id,
            'algorithm_group_id' : algorithm_group_id,
            'config' : config,
            'is_enable' : is_enable,
        } 
        db_insert(tableName, data)
    return ok('')

@bluePrint.route('/edit', methods=["post"])
def edit():
    id = assign_value(request.json, "id")
    keys_not_add = ['id','sensor_name','device_name','name','m_code','m_name']
    addModel = {key: request.json[key]
                    for key in request.json if key not in keys_not_add}
    return db_update(tableName,addModel,f"where id =%s", {"id": id})

@bluePrint.route('delete', methods=['post'])
def delete():
    id = request.json['id']
    return db_delete(tableName, f"where id = %s", {'mid': id})

@bluePrint.route("/status",methods=['post'])
def status1():
    a = request.json
    id = assign_value(a,"id")
    is_enable = assign_value(a,"is_enable")
    return db_update(tableName,{"is_enable",is_enable}, f'WHERE id = %s',{'id': id})